package com.qf.service.impl;

import com.alibaba.fastjson.JSON;
import com.qf.common.R;
import com.qf.mapper.AdminMapper;
import com.qf.mapper.impl.AdminMapperImpl;
import com.qf.pojo.Admin;
import com.qf.service.AdminService;
import com.qf.utils.CookieUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class AdminServiceImpl implements AdminService {
    private AdminMapper adminMapper = new AdminMapperImpl();

    /**
     * 修改管理员密码
     * @param request
     * @param response
     */
    @Override
    public void modify(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String newPassword = request.getParameter("newPassword");
        if (username == null && password == null || newPassword == null) {
            request.setAttribute("msg", "请确保各项不能为空");
            response.getWriter().write(JSON.toJSONString(R.fail("修改失败，信息没有填完")));

            return;
        }
        Admin admin = adminMapper.getAdmin(username, password);
        if (admin == null) {
            request.setAttribute("msg", "原密码错误");
            response.getWriter().write(JSON.toJSONString(R.fail("修改失败，原密码错误")));

            return;
        }
        adminMapper.update(username, newPassword);
        request.getSession().setAttribute("name", null);
        response.addCookie(CookieUtils.createCookie("name", null, 0));
        response.getWriter().write(JSON.toJSONString(R.success("修改失败，信息没有填完",null)));

    }
}
